package queue;

/**
 * @author tong
 * @date 2021/12/21 14:46
 * 数组环形队列 rear指向队尾下一个位置-front=rear时队空
 */
public class ArrayQueue {
    private int maxSize;
    private int front;
    private int rear;
    private int[] arr;

    public ArrayQueue() {
        this(10);
    }

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    public void addQueue(int data) {
        if (isFull()) {
            System.out.println("full");
            return;
        }
        arr[rear] = data;
        rear = (rear + 1) % maxSize;
    }

    public boolean isEmpty() {
        return rear == front;
    }

    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("empty");
        }
        int data = arr[front];
        front = (front + 1) % maxSize;
        return data;
    }

    public void showQueue() {
        if (isEmpty()) {
            System.out.println("empty");
            return;
        }
        int size = getSize();
        for (int i = front; i < size+front; i++) {
            System.out.printf("arr[%d]=%d\n", i%maxSize, arr[i%maxSize]);
        }
    }

    public int getSize() {
        return (rear - front + maxSize) % maxSize;
    }

    public int headQueue() {
        return arr[front];
    }
}
